import React, { useState, useEffect } from 'react';
import {
  Container,
  Typography,
  Box,
  Paper,
  Tabs,
  Tab,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Button,
  Alert,
  Card,
  CardContent,
  Grid,
  CircularProgress,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions
} from '@mui/material';
import { ethers } from 'ethers';

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`profile-tabpanel-${index}`}
      aria-labelledby={`profile-tab-${index}`}
      {...other}
    >
      {value === index && <Box sx={{ p: 3 }}>{children}</Box>}
    </div>
  );
}

const Profile = ({ user }) => {
  const [account, setAccount] = useState('');
  const [activeTab, setActiveTab] = useState(0);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [creditHistory, setCreditHistory] = useState([]);
  const [transactions, setTransactions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [userData, setUserData] = useState(null);
  const [latestProof, setLatestProof] = useState(null);
  const [repayDialogOpen, setRepayDialogOpen] = useState(false);
  const [selectedTransaction, setSelectedTransaction] = useState(null);
  const [systemBalance, setSystemBalance] = useState(0);
  const [isAdmin, setIsAdmin] = useState(false);

  const fetchUserData = async () => {
    try {
      setLoading(true);
      // 获取用户信息
      const userResponse = await fetch(`http://localhost:3001/api/user/${user.id}`);
      const userData = await userResponse.json();

      if (userData.success) {
        setUserData(userData.user);
        setIsAdmin(userData.user.role === 'admin');
      }

      // 获取信用历史
      const creditResponse = await fetch(`http://localhost:3001/api/credit-history/${user.id}`);
      const creditData = await creditResponse.json();

      if (creditData.success) {
        setCreditHistory(creditData.creditHistory);
      }

      // 获取交易历史
      const transactionsResponse = await fetch(`http://localhost:3001/api/transactions/${user.id}`);
      const transactionsData = await transactionsResponse.json();

      if (transactionsData.success) {
        setTransactions(transactionsData.transactions);
      }

      // 获取最新信用证明
      const proofResponse = await fetch(`http://localhost:3001/api/credit-proofs/${user.id}/latest`);
      const proofData = await proofResponse.json();

      if (proofData.success) {
        setLatestProof(proofData.proof);
      }

      // 如果是管理员，获取系统余额
      if (userData.user.role === 'admin') {
        const balanceResponse = await fetch('http://localhost:3001/api/system-balance');
        const balanceData = await balanceResponse.json();
        if (balanceData.success) {
          setSystemBalance(balanceData.balance);
        }
      }

      setLoading(false);
    } catch (err) {
      console.error('获取用户数据失败:', err);
      setError('获取用户数据失败');
      setLoading(false);
    }
  };

  useEffect(() => {
    if (user) {
      fetchUserData();
    }
  }, [user]);

  const handleConnectWallet = async () => {
    try {
      if (window.ethereum) {
        const provider = new ethers.providers.Web3Provider(window.ethereum);
        await provider.send('eth_requestAccounts', []);
        const signer = provider.getSigner();
        const address = await signer.getAddress();
        setAccount(address);
        // TODO: Load user data
      } else {
        setError('Please install MetaMask to use this feature');
      }
    } catch (err) {
      setError('Failed to connect wallet: ' + err.message);
    }
  };

  const handleTabChange = (event, newValue) => {
    setActiveTab(newValue);
  };

  const handleRepay = (transaction) => {
    setSelectedTransaction(transaction);
    setRepayDialogOpen(true);
  };

  const handleConfirmRepay = async () => {
    try {
      const response = await fetch('http://localhost:3001/api/repay', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userId: user.id,
          transactionId: selectedTransaction.id
        }),
      });

      const data = await response.json();

      if (data.success) {
        setSuccess(`还款成功！信用分${data.scoreChange > 0 ? '增加' : '减少'}${Math.abs(data.scoreChange)}分`);
        setRepayDialogOpen(false);
        // 刷新数据
        fetchUserData();
      } else {
        setError(data.message || '还款失败');
      }
    } catch (err) {
      setError('网络错误，请稍后重试');
    }
  };

  const handleCopyVerificationCode = () => {
    if (latestProof?.verificationCode) {
      navigator.clipboard.writeText(latestProof.verificationCode);
      setSuccess('验证码已复制到剪贴板');
    }
  };

  if (!user) {
    return (
      <Container maxWidth="md" sx={{ mt: 4 }}>
        <Alert severity="warning">请先登录</Alert>
      </Container>
    );
  }

  if (loading) {
    return (
      <Container maxWidth="md" sx={{ mt: 4, textAlign: 'center' }}>
        <CircularProgress />
      </Container>
    );
  }

  if (error) {
    return (
      <Container maxWidth="md" sx={{ mt: 4 }}>
        <Alert severity="error">{error}</Alert>
      </Container>
    );
  }

  return (
    <Container maxWidth="md" sx={{ mt: 4 }}>
      <Grid container spacing={3}>
        <Grid item xs={12}>
          <Card>
            <CardContent>
              <Typography variant="h5" gutterBottom>
                个人资料
              </Typography>
              <Box sx={{ mt: 2 }}>
                <Typography variant="body1">
                  用户名：{userData?.username}
                </Typography>
                <Typography variant="body1" color="primary" sx={{ mt: 1 }}>
                  当前余额：{(userData?.balance || 0).toFixed(2)} 元
                </Typography>
                <Typography variant="body1" sx={{ mt: 1 }}>
                  信用评分：{userData?.creditScore || 0}
                </Typography>
                {isAdmin && (
                  <Typography variant="body1" color="secondary" sx={{ mt: 1 }}>
                    系统总余额：{systemBalance.toFixed(2)} 元
                  </Typography>
                )}
                {latestProof && (
                  <Box sx={{ mt: 2, p: 2, bgcolor: 'background.paper', borderRadius: 1 }}>
                    <Typography variant="subtitle1" gutterBottom>
                      最新验证码
                    </Typography>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <Typography variant="body2" sx={{ fontFamily: 'monospace' }}>
                        {latestProof.verificationCode}
                      </Typography>
                      <Button
                        size="small"
                        variant="outlined"
                        onClick={handleCopyVerificationCode}
                      >
                        复制
                      </Button>
                    </Box>
                    <Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: 'block' }}>
                      有效期至：{new Date(latestProof.expiresAt).toLocaleString()}
                    </Typography>
                  </Box>
                )}
              </Box>
            </CardContent>
          </Card>
        </Grid>

        {isAdmin && (
          <Grid item xs={12}>
            <Paper sx={{ p: 3 }}>
              <Typography variant="h5" gutterBottom>
                系统交易记录
              </Typography>
              <TableContainer>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>用户</TableCell>
                      <TableCell>金额</TableCell>
                      <TableCell>类型</TableCell>
                      <TableCell>时间</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {transactions.map((tx, index) => (
                      <TableRow key={index}>
                        <TableCell>{tx.user}</TableCell>
                        <TableCell>{tx.amount}</TableCell>
                        <TableCell>{tx.transactionType}</TableCell>
                        <TableCell>{new Date(tx.timestamp).toLocaleString()}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            </Paper>
          </Grid>
        )}

        <Grid item xs={12}>
          <Paper sx={{ p: 3 }}>
            <Typography variant="h5" gutterBottom>
              信用历史
            </Typography>

            {error && (
              <Alert severity="error" sx={{ mb: 2 }}>
                {error}
              </Alert>
            )}

            {success && (
              <Alert severity="success" sx={{ mb: 2 }}>
                {success}
              </Alert>
            )}

            {loading ? (
              <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
                <CircularProgress />
              </Box>
            ) : (
              <TableContainer>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>时间</TableCell>
                      <TableCell>分数</TableCell>
                      <TableCell>变化</TableCell>
                      <TableCell>原因</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {creditHistory.map((record, index) => (
                      <TableRow key={index}>
                        <TableCell>{new Date(record.timestamp).toLocaleString()}</TableCell>
                        <TableCell>{record.score}</TableCell>
                        <TableCell>
                          <Typography
                            color={record.change > 0 ? 'success.main' : 'error.main'}
                          >
                            {record.change > 0 ? '+' : ''}{record.change}
                          </Typography>
                        </TableCell>
                        <TableCell>{record.description}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            )}
          </Paper>
        </Grid>
      </Grid>

      {/* 还款确认对话框 */}
      <Dialog open={repayDialogOpen} onClose={() => setRepayDialogOpen(false)}>
        <DialogTitle>确认还款</DialogTitle>
        <DialogContent>
          <Typography>
            您确定要还款 {selectedTransaction?.amount} 元吗？
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
            当前余额：{userData?.balance || 0} 元
          </Typography>
          {userData && userData.balance < (selectedTransaction?.amount || 0) && (
            <Alert severity="warning" sx={{ mt: 2 }}>
              余额不足，请先充值
            </Alert>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setRepayDialogOpen(false)}>取消</Button>
          <Button
            onClick={handleConfirmRepay}
            variant="contained"
            color="primary"
            disabled={!userData || userData.balance < (selectedTransaction?.amount || 0)}
          >
            确认还款
          </Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};

export default Profile; 